<template>
    <div class="workable-workableTask-container">
        <el-card shadow="hover" class="mb10" v-auth="'workable:task:list'">
            <el-input size="small" v-model="search.taskName" placeholder="请输入任务名称" prefix-icon="el-icon-search" style="max-width: 180px;" class="ml10"></el-input>
            <el-date-picker size="small" type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="ml10"></el-date-picker>
            <el-button size="small" icon="el-icon-search" type="primary" class="ml10" @click="onTableSearch()">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'workable:task:add'" size="small" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddWorkableTask()">新增</el-button>
            <el-button v-auth="'workable:task:edit'" size="small" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditWorkableTask()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'workable:task:remove'" size="small" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableWorkableTaskRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip></el-table-column>
				<el-table-column label="任务排序" prop="orderNum" width="100" show-overflow-tooltip align="center"></el-table-column>
				<el-table-column label="备注" prop="remark" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建者" prop="createBy" width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" show-overflow-tooltip width="100" align="center"
					v-auths="['workable:task:design', 'workable:task:run', 'workable:task:deploy', 'workable:task:edit', 'workable:task:remove']">
                    <template #default="scope">
						<el-dropdown style="margin-left: 10px;">
							<span class="el-dropdown-link">
								<el-button size="mini" type="text">操作 <i class="fa fa-angle-down"></i></el-button>
							</span>
							<template #dropdown>
								<center>
									<el-dropdown-menu>
										<el-dropdown-item>
											<el-button v-auth="'workable:task:design'" size="mini" type="text" @click="onOpenDesignWorkableTask(scope.row)">设计</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button v-auth="'workable:task:run'" size="mini" type="text" @click="onOpenRunWorkableTask(scope.row)">运行</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button v-auth="'workable:task:deploy'" size="mini" type="text" @click="onOpenDeployWorkableTask(scope.row)">部署</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button v-auth="'workable:task:edit'" size="mini" type="text" @click="onOpenEditWorkableTask(scope.row)">修改</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button v-auth="'workable:task:remove'" size="mini" type="text" @click="onTabelRowDel(scope.row)">删除</el-button>
										</el-dropdown-item>
									</el-dropdown-menu>
								</center>
							</template>
						</el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                background
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddWorkableTask ref="addWorkableTaskRef" @submit="onTableSearch"/>
        <EditWorkableTask ref="editWorkableTaskRef" @submit="onTableSearch"/>
		<DeployWorkableTask ref="deployWorkableTaskRef" @submit="onTableSearch"/>
		<el-drawer v-model="drawer.isShow" title="运行结果" direction="rtl" size="80%"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<ResultWorkableTask ref="resultWorkableTaskRef" :taskId="drawer.taskId" :runmode="drawer.runmode"/>
		</el-drawer>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddWorkableTask from '/@/views/workable/task/addWorkableTask.vue';
import EditWorkableTask from '/@/views/workable/task/editWorkableTask.vue';
import DeployWorkableTask from '/@/views/workable/task/deployWorkableTask.vue';
import ResultWorkableTask from '/@/views/workable/result/index.vue';
import { getWorkableTaskList, delWorkableTask, runWorkableTask } from '/@/api/workable/task/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { useRouter } from 'vue-router';
export default {
    name: 'workable/task',
    components: { AddWorkableTask, EditWorkableTask, DeployWorkableTask, ResultWorkableTask },
    setup() {
		const router = useRouter();
        const tableWorkableTaskRef = ref();
        const addWorkableTaskRef = ref();
        const editWorkableTaskRef = ref();
		const deployWorkableTaskRef = ref();
		const resultWorkableTaskRef = ref();
        const state = reactive({
            search:{
                taskName: undefined,
                startTime: '',
                endTime: '',
                pageNum: 1,
                pageSize: 10,
				status: 0,
				orderBy: 'orderNum',
				isAsc: 'asc'
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            },
			drawer: {
				isShow: false,
				taskId: '',
				runmode: 0,
			},
        });

        const loadTableData = (params) => {
            getWorkableTaskList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableWorkableTaskRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.taskName = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddWorkableTask = (row: object) => {
            addWorkableTaskRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditWorkableTask = (row: object) => {
            row = row || state.tableData.selections[0];
            editWorkableTaskRef.value.openDialog(row);
        };
		// 打开工作流设计器
		const onOpenDesignWorkableTask = (row: object) =>{
			row = row || state.tableData.selections[0];
			router.push({
				path: '/workable/editor',
				query: { id : row.id, t: new Date().getTime() }
			});
		}
		// 部署计划任务
		const onOpenDeployWorkableTask = (row: object) => {
			const ids = row ? [row.id] : state.tableData.selections.map(item => item.id);
			deployWorkableTaskRef.value.openDialog({'ids' : ids});
		}
		// 运行计划任务
		const onOpenRunWorkableTask = (row: object) => {
			ElMessageBox.confirm('确定运行选中的计划任务信息吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				runWorkableTask({ids: [row.id], runmode: 0}).then((res) => {
					if(res.code === 0){
						ElMessage.success('运行成功');
						state.drawer.isShow = true;
						state.drawer.taskId = row.id;
					}
				});
			}).catch(() => {});
		}
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的计划任务信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delWorkableTask(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条计划任务信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delWorkableTask([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData();
                    }
                });
            }).catch(() => {});
        };
        // 页面加载时
        onMounted(() => {
            loadTableData();
        });
        return {
            tableWorkableTaskRef,
            addWorkableTaskRef,
            editWorkableTaskRef,
			deployWorkableTaskRef,
			resultWorkableTaskRef,
            onTableSearch,
            onResetSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddWorkableTask,
            onOpenEditWorkableTask,
			onOpenDesignWorkableTask,
			onOpenDeployWorkableTask,
			onOpenRunWorkableTask,
            onTabelRowsDel,
            onTabelRowDel,
            ...toRefs(state),
        };
    },
};
</script>